package com.kjj.user.service.impl;

import com.kjj.basic.util.AjaxResult;
import com.kjj.basic.util.MD5Utils;
import com.kjj.user.domain.Logininfo;
import com.kjj.user.dto.AccountLoginDto;
import com.kjj.user.dto.SmsCodeLoginDto;
import com.kjj.user.mapper.LogininfoMapper;
import com.kjj.user.service.ILogininfoService;
import com.kjj.basic.service.impl.BaseServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author kan
 * @since 2022-09-15
 */
@Service
public class LogininfoServiceImpl extends BaseServiceImpl<Logininfo> implements ILogininfoService {

    @Autowired
    private LogininfoMapper logininfoMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    @Override
    public AjaxResult loginAccount(AccountLoginDto dto) {
        String username = dto.getUsername();
        String password = dto.getPassword();
        Integer loginType = dto.getLoginType();
        //1 空校验
        if (StringUtils.isEmpty(username)||StringUtils.isEmpty(password)||StringUtils.isEmpty(loginType+"")){
            return AjaxResult.me().setSuccess(false).setMessage("非法登录！参数异常");
        }
        Logininfo logininfo = logininfoMapper.loadUserByAccount(dto);
        //2 通过username 从数据库中查询登录信息
        //3 登录信息存在 登录状态 验证码是否正确
        if (logininfo == null) {
            return AjaxResult.me().setSuccess(false).setMessage("用户名或密码不正确");
        }
        if (logininfo.getDisable() == 0) {
            return AjaxResult.me().setSuccess(false).setMessage("账号已被禁用，请联系客服！");
        }
        String salt = logininfo.getSalt();
        String inputPwd = MD5Utils.encrypByMd5(password + salt);
        //4 产生UUID  以token作为key返回用户信息和权限信息
        String token = UUID.randomUUID().toString();
        redisTemplate.opsForValue().set(token, logininfo, 30, TimeUnit.MINUTES);
        if (!logininfo.getPassword().equals(inputPwd))
            return AjaxResult.me().setSuccess(false).setMessage("用户名或密码不正确");
        // 5 返回token
        Map<String, Object> result = new HashMap<>();
        result.put("token", token);
        logininfo.setPassword(null);
        logininfo.setSalt(null);
        result.put("logininfo", logininfo);
        return AjaxResult.me().setData(result);
    }

    @Transactional
    @Override
    public AjaxResult loginSmsCode(SmsCodeLoginDto smsCodeLoginDto) {
        String phone = smsCodeLoginDto.getPhone();
        String verifyCode = smsCodeLoginDto.getVerifyCode();
        Integer loginType = smsCodeLoginDto.getLoginType();
        //1 空校验
        if (StringUtils.isEmpty(phone)||StringUtils.isEmpty(verifyCode)||StringUtils.isEmpty(loginType+"")){
            return AjaxResult.me().setSuccess(false).setMessage("非法登录！参数异常");
        }
        Logininfo logininfo = logininfoMapper.loadUserBySmsCode(smsCodeLoginDto);
        //2 通过手机号 从数据库中查询登录信息
        //3 登录信息存在 登录状态 验证码是否正确
        if (logininfo == null) {
            return AjaxResult.me().setSuccess(false).setMessage("手机号错误或未注册");
        }
        if (logininfo.getDisable() == 0) {
            return AjaxResult.me().setSuccess(false).setMessage("手机号已被禁用，请联系客服！");
        }
        String key ="login_sms_code_" + phone;
        String smsCodeOfRedis = (String) redisTemplate.opsForValue()
                .get(key);
        String verifyCode_redis= smsCodeOfRedis.split(":")[1];
        if (StringUtils.isEmpty(smsCodeOfRedis) && !verifyCode_redis.equals(verifyCode)){
            return AjaxResult.me().setSuccess(false).setMessage("验证码有误，请重新输入");
        }
        //4 产生UUID  以token作为key返回用户信息和权限信息
        String token = UUID.randomUUID().toString();
        redisTemplate.opsForValue().set(token, logininfo, 30, TimeUnit.MINUTES);
        // 5 返回token
        Map<String, Object> result = new HashMap<>();
        result.put("token", token);
        logininfo.setPassword(null);
        logininfo.setSalt(null);
        result.put("logininfo", logininfo);
        return AjaxResult.me().setData(result);
    }

    @Transactional
    @Override
    public AjaxResult logout(String token) {
        if (!StringUtils.isNotBlank(token)){
            return AjaxResult.me().setSuccess(false).setMessage("token为空登出失败");
        }
        Object obj = redisTemplate.opsForValue().get(token);
        System.out.println(obj);
        if (obj == null) {
            return AjaxResult.me();
        }
        Boolean delete = redisTemplate.delete(token);
        return AjaxResult.me().setSuccess(delete);
    }
}
